package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 设置响应头
        w.Header().Set("Content-Type", "text/event-stream")
        w.Header().Set("Cache-Control", "no-cache")
        w.Header().Set("Connection", "keep-alive")

        // 无限循环向客户端推送数据
        for {
            // 构造 SSE 格式的数据
            data := fmt.Sprintf("data: %s\n\n", time.Now().Format("2006-01-02 15:04:05"))

            // 将数据写入响应流
            _, err := w.Write([]byte(data))
            if err != nil {
                return
            }

            // 刷新响应流
            f, ok := w.(http.Flusher)
            if !ok {
                return
            }
            f.Flush()

            // 阻塞等待一秒钟
            time.Sleep(time.Second)
        }
    })

    // 启动 HTTP 服务器
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("Error starting server:", err)
    }
}
